package top.lingkang.fas.admin.service.impl;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.solon.service.impl.ServiceImpl;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.core.handle.Context;
import top.lingkang.fas.admin.entity.SysUserEntity;
import top.lingkang.fas.admin.mapper.SysLogininforMapper;
import top.lingkang.fas.admin.mapper.SysUserMapper;
import top.lingkang.fas.admin.service.SysUserService;
import top.lingkang.fas.admin.vo.SysUserVO;
import top.lingkang.fas.common.dto.R;

import java.time.LocalDateTime;

/**
 * 用户信息表 服务层实现。
 *
 * @author Administrator
 * @since 2025-07-20
 */
@Component
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUserEntity> implements SysUserService {

    @Inject
    private SysLogininforMapper logininforMapper;

    @Override
    public R login(String username, String password) {
        SysUserEntity entity = getOne(
                QueryWrapper.create()
                        .eq(SysUserEntity::getUserName, username)
        );
        if (entity == null) {
            logininforMapper.add(username, "0", "用户不存在");
            return R.fail("账号不存在或密码错误");
        }
        // admin123  md5 -->  0192023a7bbd73250516f069df18b500
        if (!entity.getPassword().equals(SaSecureUtil.md5(password))) {
            logininforMapper.add(username, "0", "密码错误");
            return R.fail("账号不存在或密码错误");
        }
        logininforMapper.add(username, "1", "登录成功");
        recordLoginInfo(entity.getUserId());

        SysUserVO vo = new SysUserVO();
        BeanUtil.copyProperties(entity, vo);
        // 生成token
        StpUtil.login(entity.getUserId());
        String tokenValue = StpUtil.getTokenValue();
        SaSession session = StpUtil.getSession();
        vo.setToken(tokenValue);
        session.set("user", vo);
        return R.ok("登录成功", tokenValue);
    }

    /**
     * 记录登录信息
     */
    public void recordLoginInfo(Long userId) {
        SysUserEntity sysUser = new SysUserEntity();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(Context.current().realIp());
        sysUser.setLoginDate(LocalDateTime.now());
        updateById(sysUser);
    }
}
